<?php

/**
 * Class Curl
 * @package dar\materials\libs
 * requestMethod 封装了curl的初始化，请求，错误处理，只需传入curl的options就行 失败返回false，成功返回所请求的远程地址返回值
 * @static function get($url) 一般的get请求
 * @static function post($url,$data) post请求
 */
class Curl
{
    public static $error;

    public $ch;

    public $options;

    public function init()
    {
        $this->ch = curl_init();
    }

    public function reinit()
    {
        if ($this->ch) {
            curl_close($this->ch);
            $this->options = [];
        }
        $this->init();
    }

    public static function post($url, $data, $headers = null)
    {
        $curl = new self;
        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $data
        ];
        if ($headers) {
            $options[CURLOPT_HTTPHEADER] = $headers;
        }
        $curl->options = $options;
        return $curl->requestMethod($curl->options);
    }

    public static function get($url, $headers = null)
    {
        $curl = new self;
        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_POST => 0,
        ];
        if ($headers) {
            $options[CURLOPT_HTTPHEADER] = $headers;
        }

        return $curl->requestMethod($options);
    }

    /**
     * @param $options
     * @return bool | string 返回执行的结果，失败返回false
     */
    public function requestMethod($options)
    {
        $this->reinit();
        if (!$this->ch) {
            self::$error = 'curl init failed';
            return false;
        }
        $flag = curl_setopt_array($this->ch, $options);
        if (!$flag) {
            self::$error = 'curl_setopt_array failed:' . curl_error($this->ch);
            return false;
        }
        $result = curl_exec($this->ch);
        if (curl_errno($this->ch)) {
            self::$error = curl_error($this->ch);
            return false;
        }
        return $result;
    }

    public static function createFile($filename)
    {
        if (!is_file($filename)) {
            return false;
        }
        return curl_file_create($filename);
    }

    public function getLastError()
    {
        return self::$error;
    }

    public function __destruct()
    {
        if ($this->ch) {
            curl_close($this->ch);
            $this->ch = null;
        }
    }
}